package com.rwx.myjetpack.player

import android.os.Looper
import androidx.arch.core.executor.ArchTaskExecutor
import com.rwx.myjetpack.lifecycle.*
import com.rwx.myjetpack.myapp.MyApp

/**
 * Created by LH on 2023-05-25.
 * Time: 2023-05-25  17:25
 */
//数据容器 监听数据变化
class DataListenerContainer<T> {

    private var blocks = arrayListOf<(T?) -> Unit>()

    private val viewLifecycleProvider = hashMapOf<(T?) -> Unit, LifecycleProvider>()

    var value: T? = null
        //当数据变化的时候，通知更新
        set(value: T?) {
            //field=value
            //判断当前线程
            //如果是子线程则切换到主线程再更新

            if (Looper.getMainLooper().thread === Thread.currentThread()) {
                blocks.forEach {
                    dispatchValue(it, value)
                }
            } else {
                //创建handler post到主线程
                MyApp.handler.post {
                    blocks.forEach {
                        //it.invoke(value)
                        dispatchValue(it, value)
                    }
                }
            }

        }

    private fun dispatchValue(it: (T?) -> Unit, value: T?) {
        //判断对应View的生命周期是什么
        val viewModelProvider: LifecycleProvider? = viewLifecycleProvider[it]
        if (viewModelProvider != null &&
            viewModelProvider.isAtleast(LifeState.START)
        ) {
            println("更新UI...")
            it.invoke(value)


        }

    }


    /**
     * 可能会对多个View对数据进行监听，每个View对应一个owner
     * owner-block  owner对应的block  进行管理
     */
    fun addListener(owner: ILifecycleOwner, block: (T?) -> Unit) {

        //viewLifecycleProvider.put(block,owner.getLifecycleProvider())
        val lifecycleProvider = owner.getLifecycleProvider()
        viewLifecycleProvider[block] = lifecycleProvider

        val observerWrapper=ValueObserverWrapper(block)
        lifecycleProvider.addLifeListener(observerWrapper)

        if (!blocks.contains(block)) {
            blocks.add(block)
        }
    }

    inner class ValueObserverWrapper(private val valueObserver:(T?) -> Unit):AbsLifecycle(){
        override fun onViewLifeStateChange(state: LifeState) {

            //当监听到当前的View生命周期为Destory的时候，LifecycleProvider从集合中删除
            if(state==LifeState.DESTORY){
                viewLifecycleProvider.remove(valueObserver)
            }
        }

    }

}